<template>
	<view>
		<view class="cu-form-group">
			<view class="title" @tap.stop="showDetail()">{{labelName}}<text class="lg text-gray cuIcon-question"></text></view>
			<input auto-height ref="myTest" :placeholder="placeholder" :name="labelPath" v-model="choseNames" :disabled="!allowInput"></input>
			<button :style="{backgroundColor:theme}" class='cu-btn shadow text-white' @tap.stop="initData()">选择</button>
		</view>
		<view class="cu-form-group" style="display:none">
			<view class="title">id</view>
			<input placeholder="请选择"  :name="path" v-model="choseIds"></input>
		</view>
		<view class="cu-modal bottom-modal" :class="modalName=='Modal'?'show':''" @tap.stop="modalName = ''">
			<view class="cu-dialog" @tap.stop="">
				<view class="cu-bar bg-white">
					<view class="action text-red" @tap.stop="clear">清空</view>
					<view class="action" :style="{color:theme}">已选择{{count}}项</view>
					<view class="action" :style="{color:theme}" @tap.stop="modalName = ''">确定</view>
				</view>
				<view>
					<view class="cu-timeline" style="text-align: left;">
						<view class="cu-item" v-for="item in choseList" :key="item.id" @tap.stop="preve(item)">
							<text class="text-black">{{item.name}}</text>
						</view>
						<view class="cu-item" v-if="isShowChose">
							<text class="text-black">请选择</text>
						</view>
					</view>
					<view style="height: 1px;"></view>
					<view class="cu-list menu" style="text-align:left;overflow-y: scroll;" :style="[{height:'calc(40vh - '+ choseList.length * 100 + 'rpx)'}]">
						<view class="cu-item" v-for="item in currentList" :key="item.id" @tap.stop="next(item)">
							<view class="content padding-lg">
								<text class="text-gray">{{item.name}}</text>
							</view>
							<switch class='expand' :checked="isCheck(item.id)" v-show="isShowCheckBox(item.isParent)" @tap.stop="" @change="checkboxConfirm($event, item)"></switch>
						</view>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		mapState
	} from 'vuex'
	export default {
		name: 'js-tree',
		behaviors: ['uni://form-field-group'],

		data() {
			return {
				modalName: "",
				// 已经选择的name
				choseNames: "",
				// 已经选择的id
				choseIds: "",
				// 当前可选择的列表
				currentList: [],
				// 已经选择的数据（TREE）
				choseList: [],
				// 已经选择的数据(checkBox)Label
				choseCheck: new Map(),
				treeData: []
			};
		},
		mounted() {
			this.choseIds = this.value
			this.choseNames = this.labelValue
		},
		computed: {
			...mapState(["theme"]),
			isShowChose() {
				// 所有选中的都是父节点 则显示【请选择】三个字
				return this.choseList.length == (this.choseList.filter(item => item.isParent == true)).length
			},
			isShowCheckBox(isParent) {
				// 是否显示复选框
				return function(isParent) {
					return isParent ? this.checkbox && this.canSelectParent : this.checkbox
				}
			},
			isCheck(id) {
				// 是否选中
				return function(id) {
					return this.choseCheck.get(id) != null;
				}
			},
			count(){
				if(this.choseIds){
					return this.choseIds.split(",").length
				}
				return 0
			}
		},
		props: {
			url: {
				type: String,
				default: ''
			},
			//  绑定form上model中属性的值
			path: {
				type: String,
				default: '',
			},
			// 隐藏域名称
			name: {
				type: String,
				default: '',
			},
			// 隐藏域值
			value: {
				type: String,
				default: '',
			},
			// 
			defaultValue: {
				type: String,
				default: '',
			},
			labelPath: {
				type: String,
				default: '',
			},
			labelName: {
				type: String,
				default: '',
			},
			labelValue: {
				type: String,
				default: '',
			},
			defaultValue: {
				type: String,
				default: '',
			},
			placeholder: {
				type: String,
				default: '',
			},
			readonly: {
				type: Boolean,
				default: false,
			},
			allowInput:{
				type: Boolean,
				default: false
			},
			// 是否支持多选
			checkbox: {
				type: Boolean,
				default: false,
			},
			// 是否支持选择父级节点
			canSelectParent: {
				type: Boolean,
				default: false,
			},
			// 是否返回全路径
			returnFullName: {
				type: Boolean,
				default: false,
			},
			// 是否返回全路径，的分隔符，默认“/”
			returnFullNameSplit: {
				type: String,
				default: '/',
			}
		},
		methods: {
			showDetail(){
				uni.showModal({
				    title: '提示',
				    content: this.choseNames,
				    success: function (res) {
				        if (res.confirm) {
				           
				        } else if (res.cancel) {
				           
				        }
				    }
				});
			},
			initData(){
				this.modalName = 'Modal'
				this.choseList = []
				this.$request({
					url: this.url,
					success: (res)=>{
						this.treeData =  res.data;
						for(let i = 0; i < this.treeData.length; i++){
							this.treeData[i].id = this.treeData[i].id.replace("u_", "")
						}
						// 取得第一层数据
						if(this.value){
							// 获取默认值
							if(this.checkbox){
								let end = null;
								let checkValue =  this.value.split(",")
								this.treeData.forEach((value, key) => {
									if(checkValue.indexOf(value.id) != -1){
										this.choseCheck.set(value.id, value)
										end = value
									}
								})
								// 默认显示
								let current = end
								this.currentList = this.treeData.filter(item => item.pId == current.pId)
								// 默认显示
								this.ergodic(current)
							} else {
								let current =  this.treeData.filter(item => item.id == this.value)[0]
								this.currentList = this.treeData.filter(item => item.pId == current.pId)
								// 默认显示
								this.ergodic(current)
							}
						} else {
							this.currentList = this.treeData.filter(item => item.pId == '0')
						}
					}
				})
			},
			// 清空
			clear(){
				this.choseNames='';
				this.choseIds='';
				this.choseList=[];
				this.choseList = [];
				this.choseCheck =  new Map();
				this.currentList = this.treeData.filter(item => item.pId == "0")
			},
			// 点击进入下一层
			next(parent) {
				// 遍历所有选中的节点节点
				this.choseList = [];
				this.ergodic(parent)
				/* this.choseNames = this.choseList.map((item)=>{return item.name}).join(",");
				this.choseIds = this.choseList.map((item)=>{return item.id}).join(","); */
				if (!this.checkbox) {
					if(this.canSelectParent){
						if(this.returnFullName){
							this.choseNames = this.getAllLabel(this.choseList[this.choseList.length - 1].id)
							this.choseIds = this.choseList[this.choseList.length - 1].id
						} else {
							this.choseNames = this.choseList[this.choseList.length - 1].name
							this.choseIds = this.choseList[this.choseList.length - 1].id
						}
					} else if(parent.isParent == null || parent.isParent == false){
						if(this.returnFullName){
							this.choseNames = this.getAllLabel(this.choseList[this.choseList.length - 1].id)
							this.choseIds = this.choseList[this.choseList.length - 1].id
						} else {
							this.choseNames = this.choseList[this.choseList.length - 1].name
							this.choseIds = this.choseList[this.choseList.length - 1].id
						}
					}
				}
				this.currentList = this.treeData.filter(item => item.pId == parent.id)
			},
			preve(children){
				if(children.pId == "0"){
					this.currentList = this.treeData.filter(item => item.pId == "0")
				} else {
					this.currentList = this.treeData.filter(item => item.pId == children.pId)
				}
			},
			// 遍历所有
			ergodic(parent) {
				this.choseList.unshift(parent)
				if (parent.pId != "0") {
					this.ergodic(this.treeData.filter(item => item.id == parent.pId)[0])
				}
			},
			// 多选框选中
			checkboxConfirm(e, chose) {
				if (e.detail.value) {
					this.choseCheck.set(chose.id, chose)
				} else {
					this.choseCheck.delete(chose.id)
				}
				let choseNames = [];
				let choseIds = [];
				this.choseCheck.forEach((value, key) => {
					choseNames.push(this.getAllLabel(value.id))
					choseIds.push(key)
				})
				this.choseNames = choseNames.join(",")
				this.choseIds = choseIds.join(",")
			},
			// 返回全路径
			getAllLabel(choseIds){
				if (choseIds != "0") {
					let current = this.treeData.filter(item => item.id == choseIds)[0]
					let parent = this.getAllLabel(current.pId)
					 if(parent){
						 return  parent + this.returnFullNameSplit + current.name
					 } else {
						 return parent + current.name
					 }
				} else {
					return ""
				}
			}
		}
	}
</script>

<style scoped>
	.cu-list .cu-item {
		padding-left: 30rpx;
	}
	.cu-form-group{
		border-top:null;
		border-bottom:1rpx solid #eee;
	}
	.expand{
		padding:10px;
	}
</style>
